<?php

/**
 * @author Ahmet YUCEL
 * @copyright 2011
 */

class scoringComponent extends object{
    
    function initialize(&$controller, $settings = array()) {    
        $this->controller =& $controller;
        $this->Brand = ClassRegistry::init('Brand');
        $this->BrandUrl = ClassRegistry::init('BrandUrl');
        $this->BrandUrlValue = ClassRegistry::init('BrandUrlValue');
        
        $this->alexaBandUrlId = 0;
        $this->highRank = 0;
        $this->lowRank = 0;        
    }
    
    function getMaxAndMinValues()
    {        
        $alexaBrand = $this->BrandUrl->find('first',array('conditions'=>array('BrandUrl.system_name'=>'alexa')));
        $this->alexaBandUrlId = $alexaBrand['BrandUrl']['id'];
        $this->highRank = $this->BrandUrlValue->find('first',array('conditions'=>array('BrandUrlValue.brand_url_id'=>$this->alexaBandUrlId),'order'=>array('BrandUrlValue.value DESC')));
        //$this->lowRank = $this->BrandUrlValue->find('first',array('conditions'=>array('BrandUrlValue.brand_url_id'=>$this->alexaBandUrlId),'order'=>array('BrandUrlValue.value ASC')));        
    }
    
    function getWeights()
    {
        $brands = $this->BrandUrl->activeData();
        $this->weights = array();
        foreach($brands as $brand)
        {
            $this->weights[$brand['BrandUrl']['id']] = $brand['BrandUrl']['weight']/100;
        }        
    }
    
    function calculate($records=null)
    {
        $this->getMaxAndMinValues();
        $this->getWeights(); 
        if($records==null) $records = $this->Brand->getActiveBrands();        
        foreach($records as $record)
        {
            $total = 0;			
            foreach($record['BrandUrlValue'] as $brandUrlValue) {               				
                /* calculate the score for alexa API */
				if($brandUrlValue['brand_url_id']==$this->alexaBandUrlId)
                {
					$total += $this->calculateRank($brandUrlValue['value'],$this->highRank['BrandUrlValue']['value']) * $this->weights[$brandUrlValue['brand_url_id']];
                }
				/* calculate the score for other APIs */
                else
                {
                    $total += $brandUrlValue['value'] * $this->weights[$brandUrlValue['brand_url_id']];
                }                
            }         
            //debug($total);   
            $this->Brand->id = $brandUrlValue['brand_id'];            
            $this->Brand->save(array('Brand'=>array('points'=>$total)));
        }       
    }    
    
    function calculateRank($rank,$max)
    { 
	   return (int)$max - (int)$rank;    
    }
}

?>